<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    :maskClosable="false"
    :defaultFullscreen="isUpdate"
    :enableComment="isUpdate"
    @ok="handleSubmit"
    width="900px"
  >
    <BasicForm @register="registerForm">
      <template #planColorPicker>
        <div>
          <CalendarColorPicker :colorList="HEADER_PRESET_BG_COLOR_LIST" :def="planColor" @change="handleChangeplanColor" :disabled="!isResponsible" />
        </div>
      </template>
    </BasicForm>
    <template #centerFooter v-if="isUpdate && isResponsible">
      <a-button type="primary" danger @click="handleDeleteClick">删 除</a-button>
    </template>
    <template #comment>
      <CommentPanel :dataId="dataId" :tableName="tableName" :showComment="true" :showFiles="true" :showDataLog="true" />
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema, HEADER_PRESET_BG_COLOR_LIST } from './calendar.data';
  import { saveOrUpdateTask, getTaskById, deleteTask } from './calendar.api';
  import { dateFormat } from '/@/utils/common/compUtils';
  import CalendarColorPicker from './components/CalendarColorPicker.vue';
  import CommentPanel from '/@/components/jeecg/comment/CommentPanel.vue';
  import { isString } from '/@/utils/is';
  import moment from 'moment-timezone';
  import { useUserStore } from '/@/store/modules/user';
  import { message } from 'ant-design-vue';

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const userStore = useUserStore();
  const isUpdate = ref(true);
  const isResponsible = ref(true);
  const fieldTime = ref<[String, String]>();
  const planColor = ref('');
  const dataId = ref('');
  const tableName = ref('sys_calendar');
  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    dataId.value = data?.id;
    fieldTime.value = data?.fieldTime;
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //编辑模式下禁用id字段
      updateSchema({ field: 'id', dynamicDisabled: true });
      //获取详情
      data.record = await getTaskById({ id: data.id });
      data.record.rangeTime = [data.record.beginDate, data.record.endDate];
      planColor.value = data.record.planColor;
      isResponsible.value = userStore.getUserInfo.id == data.record.createBy;
      //非负责人创建的禁用字段
      if (!isResponsible.value) {
        updateSchema({ field: 'id', dynamicDisabled: true });
        updateSchema({ field: 'title', dynamicDisabled: true });
        updateSchema({ field: 'type', dynamicDisabled: true });
        updateSchema({ field: 'remindType', dynamicDisabled: true });
        updateSchema({ field: 'urgentLevel', dynamicDisabled: true });
        updateSchema({ field: 'reminderTime', dynamicDisabled: true });
        updateSchema({ field: 'reminds', dynamicDisabled: true });
        updateSchema({ field: 'rangeTime', dynamicDisabled: true });
        updateSchema({ field: 'allDay', dynamicDisabled: true });
        updateSchema({ field: 'joinPerson', dynamicDisabled: true });
        updateSchema({ field: 'remark', dynamicDisabled: true });
        updateSchema({ field: 'files', dynamicDisabled: true });
        updateSchema({ field: 'imgs', dynamicDisabled: true });
      }
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    } else {
      updateSchema({ field: 'id', dynamicDisabled: false });
      updateSchema({ field: 'id', dynamicDisabled: false });
      updateSchema({ field: 'title', dynamicDisabled: false });
      updateSchema({ field: 'type', dynamicDisabled: false });
      updateSchema({ field: 'remindType', dynamicDisabled: false });
      updateSchema({ field: 'urgentLevel', dynamicDisabled: false });
      updateSchema({ field: 'reminderTime', dynamicDisabled: false });
      updateSchema({ field: 'reminds', dynamicDisabled: false });
      updateSchema({ field: 'rangeTime', dynamicDisabled: false });
      updateSchema({ field: 'allDay', dynamicDisabled: false });
      updateSchema({ field: 'joinPerson', dynamicDisabled: false });
      updateSchema({ field: 'remark', dynamicDisabled: false });
      updateSchema({ field: 'files', dynamicDisabled: false });
      updateSchema({ field: 'imgs', dynamicDisabled: false });
      planColor.value = HEADER_PRESET_BG_COLOR_LIST.filter((item) => item.id == 5)[0].color;
      // 日程时间赋值
      let beginDate = moment(new Date()).format('YYYY-MM-DD');
      let endDate = moment(new Date()).format('YYYY-MM-DD');
      if (fieldTime.value && fieldTime.value.length > 0) {
        beginDate = moment(new Date(fieldTime.value[0])).format('YYYY-MM-DD');
        endDate = moment(new Date(fieldTime.value[1])).format('YYYY-MM-DD');
      }
      fieldTime.value = [beginDate, endDate];
      await setFieldsValue({
        rangeTime: fieldTime.value,
      });
    }
  });
  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增日程计划' : '编辑日程计划'));
  //表单提交事件
  async function handleSubmit(v) {
    try {
      if (isUpdate.value && !isResponsible.value) {
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success');
      }
      let values = await validate();
      let beginDate = '';
      let endDate = '';
      if (isString(values.rangeTime)) {
        const dateSplits = values.rangeTime.split(',');
        if (dateSplits.length > 2) {
          //Tue, 05 Sep 2023 00:00:00 GMT,Tue, 05 Sep 2023 00:00:00 GMT
          const bdString = dateSplits[0] + ',' + dateSplits[1];
          const edString = dateSplits[2] + ',' + dateSplits[3];
          beginDate = dateFormat(bdString, 'yyyy-MM-dd hh:mm:ss');
          endDate = dateFormat(edString, 'yyyy-MM-dd hh:mm:ss');
        } else {
          beginDate = dateFormat(dateSplits[0], 'yyyy-MM-dd hh:mm:ss');
          endDate = dateFormat(dateSplits[1], 'yyyy-MM-dd hh:mm:ss');
        }
      } else {
        beginDate = dateFormat(values.rangeTime[0], 'yyyy-MM-dd hh:mm:ss');
        endDate = dateFormat(values.rangeTime[1], 'yyyy-MM-dd hh:mm:ss');
      }
      //delete values.rangeTime;
      values.planColor = planColor.value;
      let params = Object.assign({}, { beginDate: beginDate, endDate: endDate }, values);
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdateTask(params, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 删除
  async function handleDeleteClick() {
    try {
      if (isUpdate.value && !isResponsible.value) {
        message.error('无权限操作');
      }
      let values = await validate();
      let params = Object.assign({}, values);
      setModalProps({ confirmLoading: true });
      //删除
      await deleteTask(params, function () {
        //关闭弹窗
        closeModal();
        //刷新列表
        emit('success');
      });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  // 颜色变更
  function handleChangeplanColor(color) {
    planColor.value = color;
  }
</script>
